package com.juku2024.juku.viewmodel

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.juku2024.juku.R
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.SearchHistoryEntity
import com.juku2024.juku.db.entity.HotSearchModel
import com.juku2024.juku.model.SearchRequest
import com.juku2024.juku.model.SearchResultModel
import com.juku2024.juku.network.api.Api
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.request.HotSearchRequest
import com.juku2024.juku.tools.*
import kotlinx.coroutines.*
import kotlin.collections.ArrayList

class SearchViewModel : BaseViewModel() {

    fun getHistorySearchList(success: (model: ArrayList<String>) -> Unit, fail: (msg: String) -> Unit) {
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO) {
                val count = NoteRoomUtils.getInstance().searchKeywordsDao().queryKeywordsCount() ?: 0
                if (count > 10) {
                    LogC.e("删除多余条目")
                    NoteRoomUtils.getInstance().searchKeywordsDao().deleteBatch((count - 10).toInt())
                }
                return@withContext NoteRoomUtils.getInstance().searchKeywordsDao().queryKeywordsLimit(10) as ArrayList?
            }
            if (isNotActive()) return@launch
            if (result.isNullOrEmpty()) {
                fail(AppUtils.getString(R.string.error_net))
            } else {
                success(result)
            }
        }
    }



    fun getHotSearch(success: (model: HotSearchModel) -> Unit, fail: (msg: String) -> Unit) {
        doBaseHttp({
            val versionResponse = getVersion(Constants.API_TYPE_HOTSEARCH)
            var model: HotSearchModel? = null
            if (!versionResponse.isUpgrade) { // 无需更新
                model = withContext(Dispatchers.IO) { NoteRoomUtils.getInstance().hotDao().query() }
                if (model == null) {
                    withContext(Dispatchers.IO) { NoteRoomUtils.getInstance().hotDao().delete() }
                } else {
                    success(model)
                }
            }
            return@doBaseHttp model
        }, {
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(appId, getAppKey(), timestamp, getExtra())
            val request = HotSearchRequest(appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getHotSearch(appId, getCommonRequest(request))
        }, object : OnRetrofitResultListener<HotSearchModel> {
            override fun onSuccess(t: HotSearchModel) {
                RxUtils.doObservable<Int> {
                    val dao = NoteRoomUtils.getInstance().hotDao()
                    dao.delete()
                    dao.insert(t)
                    if (!it.isDisposed) {
                        it.onComplete()
                    }
                }
                if (isNotActive()) return
                success(t)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }


    fun insertHistory(content: String?) {
        //全是空格的话不存数据库
        if (TextUtils.isEmpty(content?.trim())) {
            return
        }
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    val searchKeywords = SearchHistoryEntity()
                    searchKeywords.keywords = content
                    searchKeywords.timestamp = System.currentTimeMillis()
                    NoteRoomUtils.getInstance().searchKeywordsDao().insert(searchKeywords)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun deleteSearchHistory() {
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    NoteRoomUtils.getInstance().searchKeywordsDao().deleteAll()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    fun getSearchResult(content: String?, page: Int, success: (model: SearchResultModel) -> Unit, fail: (msg: String) -> Unit) {
        if (TextUtils.isEmpty(content)) {
            return
        }
        doBaseHttp({
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(content, 0, page, 10, appId, getAppKey(), timestamp, getExtra())
            val request = SearchRequest(keyword = content!!, genreId = 0, page = page, pageSize = 10, appId = appId, timestamp = timestamp, sign = sign)
            return@doBaseHttp  if (BaseApplication.isLimited) {
                RetrofitUtils.instance.getApi(Api::class.java).getGenuineSearch(getCommonRequest(request))
            } else {
                RetrofitUtils.instance.getApi(Api::class.java).getSearch(getCommonRequest(request))
            }
        }, object : OnRetrofitResultListener<SearchResultModel> {
            override fun onSuccess(t: SearchResultModel) {
                if (isNotActive()) return
                success(t)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }

//    private var disposable: Disposable? = null
//    fun getAutoSearchKey(keyword: String?, success: (model: ArrayList<AutomateModel.Item>) -> Unit, fail: () -> Unit){
//        if (TextUtils.isEmpty(keyword)) return
//        disposable?.dispose()
//        val request = SearchRequest(keyword!!, 1)
//        disposable = RetrofitUtils.instance.getApi(Api::class.java).automate(request)
//            .subscribeOn(Schedulers.io())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe({
//                if (it.data.isNullOrEmpty()) {
//                    fail()
//                } else {
//                    success(it.data!!)
//                }
//            },{
//                fail()
//            })
//    }

}